package redisconn

import (
	"time"

	"github.com/garyburd/redigo/redis"
)

var Rc redis.Conn

type DbnoPool struct {
	pool redis.Pool
	dbno int
}

func init() {
	Rc = newRdsPool(`10.42.0.23:6379`, "sOd3bZBFgdVyGRWC", 3).Get()
}

func (p *DbnoPool) Get() redis.Conn {
	conn := p.pool.Get()
	conn.Do("SELECT", p.dbno)
	return conn
}

func newRdsPool(server, auth string, dbno int) *DbnoPool {
	pool := &DbnoPool{
		redis.Pool{
			MaxIdle:     100,
			MaxActive:   30,
			IdleTimeout: 60 * time.Second,
			Dial: func() (redis.Conn, error) {
				c, err := redis.Dial("tcp", server)
				if err != nil {
					return nil, err
				}
				if auth == "" {
					return c, err
				}
				if _, err := c.Do("AUTH", auth); err != nil {
					c.Close()
					return nil, err
				}
				return c, err
			},
			TestOnBorrow: func(c redis.Conn, t time.Time) error {
				_, err := c.Do("PING")
				return err
			},
		},
		dbno,
	}
	return pool
}
